//
//  XLocalizedBundle.m
//  International_Lab
//
//  Created by Xu Deheng on 12-8-10.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "XLocalizedBundle.h"

@interface XLocalizedBundle ()


@end

static NSBundle *_localizedBundle = nil;
static NSString *_localizationIdentifier = nil;
static NSString *_tableListName = nil;

@implementation XLocalizedBundle

+ (NSBundle *)currentBundle
{
    if (!_localizedBundle) {
        [self setLocalizationIdentifier:[[NSLocale currentLocale] localeIdentifier]];
    }
    return _localizedBundle;
}

+ (void)setLocalizationIdentifier:(NSString *)localizationIdentifier
{
    if (_localizationIdentifier && [_localizationIdentifier isEqualToString:localizationIdentifier])  {
        return;
    }
    
    @synchronized(self){
        [_localizationIdentifier release];
        _localizationIdentifier = [localizationIdentifier copy];
        
        [_localizedBundle release];
        _localizedBundle = nil;
        
        NSString *path = [[NSBundle mainBundle] pathForResource:localizationIdentifier ofType:@"lproj"];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:path] || !localizationIdentifier) {
            _localizedBundle = [[NSBundle mainBundle] retain];
        }else {
            _localizedBundle = [[NSBundle bundleWithPath:path] retain];
        }
    }
}

+ (void)setTableListName:(NSString *)table
{
    @synchronized(self){
        [_tableListName release];
        _tableListName = [table copy];
    }
}

+ (NSString *)localizedStringWithKey:(NSString *)thekey andValue:(NSString *)value
{
    return [self localizedStringWithKey:thekey andValue:value fromTable:_tableListName];
}

+ (NSString *)localizedStringWithKey:(NSString *)thekey andValue:(NSString *)value fromTable:(NSString *)table
{
    return [_localizedBundle localizedStringForKey:thekey value:value table:table];
}

#pragma mark - singleton pattern
- (id)init
{
    assert(1 == 0);
    self = [super init];
    return self;
}

- (id)autorelease
{
    return self;
}

- (oneway void)release
{
}

- (id)copy
{
    return self;
}

- (id)retain
{
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

@end
